package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.dto.WmUserDto;
import com.heima.model.common.wemedia.pojo.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-06-02
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {

        LambdaQueryWrapper<WmUser> queryWapper = new LambdaQueryWrapper<>();
        queryWapper.eq(WmUser::getName,dto.getName());
        queryWapper.eq(WmUser::getStatus,1);
        WmUser wmUser = getOne(queryWapper);
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        String s = DigestUtils.md5DigestAsHex((dto.getPassword()+wmUser.getSalt()).getBytes());
        if (!s.equals(wmUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        Map<String,Object> map = new HashMap<>();
        wmUser.setPassword("");
        wmUser.setSalt("");
        map.put("user",wmUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
